<template>
  <div>
    <div ref="editor"></div>
  </div>
</template>

<script>
import wangEditor from "wangeditor";

export default {
  props: {
    wangeditorConfig: {
      height: '',
      onchangeTimeout: '',
      uploadImgServer: '',
      uploadFileName: '',
      uploadImgMaxSize: '',
      uploadImgMaxLength: '',
    }
  },
  data() {
    return {
      editor: null,
    };
  },
  mounted() {
    this.initEditor();
  },
  methods: {
    initEditor() {
      if (this.editor) {
        this.editor.destroy() // 如果已经创建，则销毁编辑器
      }
      this.editor = new wangEditor(this.$refs.editor);
      this.editor.config.height = this.wangeditorConfig.height
      this.editor.config.onchange = (html) => {
        this.$emit("input", html);
      };
      // 配置触发 onchange 的时间频率，默认为 200ms
      this.editor.config.onchangeTimeout = this.wangeditorConfig.onchangeTimeout; // 修改为 500ms
      // 插入网络图片的回调
      this.editor.config.linkImgCallback = function (src) {
        console.log('图片 src ', src)
        //console.log('图片文字说明',alt)
        //console.log('跳转链接',href)
      }
      // 自定义检查插入视频的回调
      this.editor.config.onlineVideoCallback = function (video) {
        // 自定义回调内容，内容成功插入后会执行该函数
        console.log('插入视频内容', video)
      }
      //关闭样式过滤
      this.editor.config.pasteFilterStyle = false
      // 配置 server 接口地址
      this.editor.config.uploadImgServer = this.wangeditorConfig.uploadImgServer
      this.editor.config.withCredentials = true
      this.editor.config.uploadFileName = this.wangeditorConfig.uploadFileName
      this.editor.config.uploadImgMaxSize = this.wangeditorConfig.uploadImgMaxSize //最大上传5M的图片
      this.editor.config.uploadImgMaxLength = this.wangeditorConfig.uploadImgMaxLength // 一次最多上传 1 个图片
      this.editor.config.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
          //console.log(result.data)
          var url = result.data.url;//获取后台返回的url
          insertImg(url);
        }
      };
      //this.editor.config.uploadImgShowBase64 = true
      this.editor.config.uploadVideoServer = this.wangeditorConfig.uploadImgServer // 上传接口
      this.editor.config.uploadVideoParams = {
        'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarycZm1pHksXeHS6t5r'
      }
      this.editor.config.uploadVideoName = this.wangeditorConfig.uploadFileName
      this.editor.config.uploadVideoHooks = {
        customInsert: function (insertVideo, result, editor) {
          var url = result.data.url;
          insertVideo(url);
        }
      }
      // 配置alt选项
      this.editor.config.showLinkImgAlt = true
      // 配置图片超链接
      this.editor.config.showLinkImgHref = true
      this.editor.create()

      console.log(this.$refs)
    },
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
    }
  },
};
</script>